//
//  PhotoDetailViewController.m
//  Paparazzi
//
//  Created by Eric Williams on 10/24/10.
//  Copyright 2010 Eric Williams. All rights reserved.
//

#import "PhotoDetailViewController.h"
#import "EXIFViewController.h"
#import "Recent.h"

@implementation PhotoDetailViewController

@synthesize imageView;
@synthesize imageScrollView;
@synthesize spinner;

@synthesize photo;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Create and animate into a photo info view
- (void) infoButtonClicked {
	EXIFViewController *exifController = [[EXIFViewController alloc] init];
	exifController.photo = photo;

	// Present the EXIF data modally
	exifController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self.navigationController presentModalViewController: exifController animated: YES];
	[exifController release];
}


// Manually implemented to enable image zooming
- (UIView *) viewForZoomingInScrollView:(UIScrollView*) scrollView {
	return self.imageView;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

	// Prepare the Flickr Fetcher
	FlickrFetcher *flickrFetcher = [FlickrFetcher sharedInstance];
	
	// Shorten the back button
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Photo" style:UIBarButtonItemStyleBordered target:nil action:nil];
	self.navigationItem.backBarButtonItem = backButton;
	[backButton release];
	
/* DONE INSIDE IB
	// Set the zoom limits
	[self.imageScrollView setMaximumZoomScale: 1.0];
	[self.imageScrollView setMinimumZoomScale: 0.5];
	
	// Set ourself as the delegate to enable zooming using the delegate method implemented in "ourself"
	self.imageScrollView.delegate = self;
*/
	
	// Create the subview image - USE A BLOCK
	NSString *photoID = photo.flickrPhotoID;
	NSString *farm = photo.flickrFarm;
	NSString *server = photo.flickrServer;
	NSString *secret = photo.flickrSecret;
	
	[self.spinner startAnimating];
	
	dispatch_queue_t flickrDetailDownloadQueue = dispatch_queue_create("Flickr Detail Downloader", NULL);
	dispatch_async(flickrDetailDownloadQueue, ^{
		NSData *imageData = [flickrFetcher dataForPhotoID:photoID fromFarm:farm onServer:server withSecret:secret inFormat: FlickrFetcherPhotoFormatLarge];
	
		dispatch_async(dispatch_get_main_queue(), ^{
			UIImage *image = [UIImage imageWithData: imageData];
	
			self.imageView.image = image;
			self.imageView.contentMode = UIViewContentModeScaleAspectFit;
			self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
			self.imageView.backgroundColor = [UIColor blackColor];
			[self.imageScrollView setContentSize: image.size];
			[self.imageScrollView setZoomScale:0.5 animated: NO];
			[self.spinner stopAnimating];
		});
	});
	dispatch_release(flickrDetailDownloadQueue);

/* TODO	
	// Save the image in our recent images collection
	NSArray *recentSingleton = [flickrFetcher fetchManagedObjectsForEntity: @"Recent" withPredicate: nil];
	Recent *recent = [recentSingleton objectAtIndex: 0];
	
	// If there are already 10, remove the oldest one
	if(recent.photos.count == 10) {
	//	NSLog([NSString stringWithFormat: @"Now removing '%@' from the recent list...",(Photo*) [recent.photos objectAtIndex: 9].name]);
	//	[recent.photos removeLastObject];
	}
	
	// Insert the newest one
	[recent addPhotosObject: photo];
	[flickrFetcher.managedObjectContext save: nil];
	
	// TEST PRINT THE CONTENTS OF RECENT
	Photo *currPhoto;
	for(currPhoto in recent.photos) {
//		NSLog([NSString stringWithFormat: @"'%@' is a recent photo", currPhoto.name]);
	}
*/	
	
/* DONE IN IB
	// Add the view hierarchy onto our controller's view
	[self.imageScrollView addSubview: self.imageView];
	[self.view addSubview: self.imageScrollView];
	[self.imageScrollView release];
	[self.imageView release];
*/
	
	// Add a button for viewing more detailed image information
	UIImageView *infoBackView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"infoBack.png"]];
	infoBackView.frame = CGRectMake(284, 14, 22, 22);
	[self.view addSubview: infoBackView];
	
	UIButton *infoButton = [UIButton buttonWithType: UIButtonTypeInfoLight];
	infoButton.frame = CGRectMake(285, 15, 20, 20);
	[self.view addSubview: infoButton];
	
	[infoButton addTarget: self action: @selector(infoButtonClicked) forControlEvents: UIControlEventTouchUpInside];
	
	// Customize the background color and title
	self.title = [photo name];
	self.view.backgroundColor = [UIColor blackColor];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	self.imageView = nil;
	self.imageScrollView = nil;
	self.spinner = nil;
	
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[imageView release];
	[imageScrollView release];
	[spinner release];
    [super dealloc];
}

@end
